const app = getApp();
const db = wx.cloud.database()
const _ = db.command;
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    bookinfo: {},
    searchvalue: ''
  },

  getDataAll: function() {
    db.collection('book').get().then(res => {
      console.log(res.data)
      this.setData({
        bookinfo: res.data
      })
    })
  },

  onLoad: function(options) {
    this.getDataAll()
  },

  getData: function(searchvalue) {
    db.collection("book").where(
        _.or([{
            title: db.RegExp({
              regexp: searchvalue,
              options: 'i',
            })
          },
          {
            ISBN: db.RegExp({
              regexp: searchvalue,
              options: 'i',
            })
          }
        ])
      )
      .get()
      .then(res => {
        console.log(res.data);
        this.setData({
          bookinfo: res.data
        })
      });
  },

  scanbook: function() {
    wx.scanCode({
      success: res => {
        console.log(res)
        this.setData({
          searchvalue: res.result
        })
        this.getData(res.result)
      }
    })
  },

  bindKeyInput: function(event) {
    this.setData({
      searchvalue: event.detail.value
    })
  },

  search: function() {
    var searchvalue = this.data.searchvalue
    if (searchvalue == '')
      this.getDataAll()
    else
      this.getData(searchvalue)
  },

  bookClick: function (event) {
    console.log(event.currentTarget.dataset.id)
    wx.navigateTo({
      url: '../bookdetail/bookdetail?id=' + event.currentTarget.dataset.id
    })
  }
})